package cn.edu.nwpu.warehousemanagement.util;

import cn.edu.nwpu.warehousemanagement.config.RsaKeyConfig;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.time.Duration;

/**
 * RSA密钥工具类
 *
 * @author Loadstar
 * @version 1.0
 */
@Component
public class RSAUtil {

    private static RsaKeyConfig rsaKeyConfig;

    /**
     * 检查时间戳是否在有效期内，并解密RSA加密的密码
     *
     * @param publicKeyTimestamp 公钥的时间戳
     * @param encryptedPassword  加密后的密码
     * @return 解密后的密码
     */
    public static String decryptRSA(long publicKeyTimestamp, String encryptedPassword) {
        // 检查时间戳是否在有效期内
        if (System.currentTimeMillis() - publicKeyTimestamp > Duration.ofDays(1).toMillis()) {
            throw new RuntimeException("公钥已过期，请刷新页面，重新获取");
        }

        return rsaKeyConfig.decrypt(encryptedPassword);
    }

    @Resource
    public void setRsaKeyConfig(RsaKeyConfig rsaKeyConfig) {
        RSAUtil.rsaKeyConfig = rsaKeyConfig;
    }
}
